package nl.leiden.activities;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

import nl.leiden.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;
import android.view.View;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;

import android.gesture.Gesture;
import android.gesture.Prediction;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;

public class WritingActivity extends Activity implements OnGesturePerformedListener {
	
	//----------------------------------------------------
	private GestureLibrary gesturesLibActions;
	private GestureLibrary gesturesLibStandard;
	private GestureLibrary gesturesLibUser;
   
	private final File gesturesLibUserFile = new File(Environment.getExternalStorageDirectory(), "gestures_lib_user");
    
    private StringBuffer sBufferGestureText = new StringBuffer();
    private String sGestureText = new String();
    //----------------------------------------------------
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_writing);
        
        //--buttons
        /*Button previous = (Button) findViewById(R.id.ButtonWritingPrevious);
        previous.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), ContactsActivity.class);
                startActivityForResult(myIntent, 0);
            }

        });

        Button next = (Button) findViewById(R.id.ButtonWritingNext);
        next.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Intent myIntent = new Intent(view.getContext(), ReviewActivity.class);
                startActivityForResult(myIntent, 0);
            }

        });*/
        
		Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		long[] pattern = {0, 200, 200, 200};
		v.vibrate(pattern, -1);
        
        //-- load gesture libraries
        gesturesLibActions = GestureLibraries.fromRawResource(this, R.raw.gestures_lib_actions);
        if(!this.gesturesLibActions.load()) {
        	this.finish();
        }
        
        gesturesLibStandard = GestureLibraries.fromRawResource(this, R.raw.gestures_lib_standard);
        if(!this.gesturesLibStandard.load()) {
        	this.finish();
        }
        
        //----TODO: CHECK IF FILE IS EXISTING OR NOT
        gesturesLibUser = GestureLibraries.fromFile(gesturesLibUserFile);
        if(!this.gesturesLibUser.load()) {
        	this.finish();
        }  
        
        //-- load preferences
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String sMessage = preferences.getString("sMessage", "");
            
        //-- reset buffer with content from preferences
        this.sBufferGestureText.delete(0, this.sBufferGestureText.length());
        this.sBufferGestureText.append( sMessage );
        this.sGestureText = sBufferGestureText.toString();
        
        //-- get gesture overlay view to add on gesture performed listener
        GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
        gestures.addOnGesturePerformedListener(this); 
        
        //-- load sMessage from preferences to TextView
        TextView tv = (TextView) findViewById(R.id.TextViewGestureText);
        tv.setText(sMessage + "|");
    }
    
    //----------------------------------------------------
    public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture) {
        	
    	//--recognize libraries
    	ArrayList<Prediction> predictionsActions = gesturesLibActions.recognize(gesture);
    	ArrayList<Prediction> predictionsStandard = gesturesLibStandard.recognize(gesture);
		ArrayList<Prediction> predictionsUser = gesturesLibUser.recognize(gesture);
				
		ArrayList<Prediction> predictionsAll = new ArrayList<Prediction>();
		predictionsAll.addAll(predictionsActions);
		predictionsAll.addAll(predictionsStandard);
		predictionsAll.addAll(predictionsUser);
			
		//--when added the other predictions, need to re sort the predictionsAll ArrayList again	
		//--http://ventrix.nsdc.gr/code_folds/?p=119
		Comparator<Prediction> comparator = new Comparator<Prediction>() {
			//@Override
			public int compare(Prediction object1, Prediction object2) {
				if( object1.score > object2.score ) {
					return -1;
				} else if (object1.score < object2.score ) {
					return 1;
				} else {
					return 0;
				}			
			}
		};
		Collections.sort(predictionsAll, comparator);
		
		//--print predictions in correct order
//		for(int i=0; i < predictionsAll.size(); i++ ) {
//			Log.d("log scores in order" , i + " = " + predictionsAll.get(i).score);
//		}
		
		//--ACTIONS------------------------------------------------
		// We want at least one prediction
		if (predictionsAll.size() > 0) {
			Prediction prediction = predictionsAll.get(0);
			/** TODO
			 * MAKE PREFERENCE SETTING FOR SENSITIVITY
			 */
			// We want at least some confidence in the result
			if (prediction.score > 1) {
				
				//--action name
				String action = predictionsAll.get(0).name;
				Log.d("action prediction 0 name = ", action);
				
				//--action: backspace
				if ("action_backspace".equals(action)) {
					if(this.sBufferGestureText.length() >= 1) {
						this.sBufferGestureText.deleteCharAt(this.sBufferGestureText.length()-1);
						this.sGestureText = this.sBufferGestureText.toString();
					} 
				}
				
				//--action: clear
				else if ("action_clear".equals(action)) {
					if(this.sBufferGestureText.length() > 1) {
						this.sBufferGestureText.delete(0, this.sBufferGestureText.length() );
						this.sGestureText = this.sBufferGestureText.toString();
					}
				}
				
				//--action: confirm
				else if ("action_confirm".equals(action)) {
					Intent myIntent = new Intent(this, ReviewActivity.class);
	                startActivityForResult(myIntent, 0);
				}
				
				//--action: goback
				else if ("action_goback".equals(action)) {					
					Intent myIntent = new Intent(this, ContactsActivity.class);
	                this.startActivity(myIntent);
				}
				
				//--action: goback
				else if ("action_add".equals(action)) {
					//empty
				}
				
				//--no action but new writing gesture
				else {
					// Show the spell
					//Toast.makeText(this, prediction.name, Toast.LENGTH_SHORT).show();
				
					//-- use a string buffer to add the new character to the message
					//-- .append at string buffer is 300 times faster than string s += " string to add"
					this.sBufferGestureText.append( prediction.name );
					this.sGestureText = sBufferGestureText.toString();
				}
				//Toast.makeText(this, prediction.name, Toast.LENGTH_SHORT).show();
				
		        //-- store update message to preferences
		        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
		        SharedPreferences.Editor editor = preferences.edit();
		        editor.putString("sMessage", this.sGestureText);
		        editor.commit();
				
				//-- set text view with updated message
				TextView tv = (TextView) findViewById(R.id.TextViewGestureText);
		        tv.setText(this.sGestureText + "|");
				
			} else {
				Toast.makeText(this, "gesture not recognized", Toast.LENGTH_SHORT).show();
			}
		}
		
//		//-- STANDARD --------------------------------------------
//		if (predictionsActions.size() > 0) {
//			Prediction prediction = predictionsActions.get(0);
		
		
	}
}